﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace Service.Core
{
    class Conn
    {
        //缓冲字节常量
        public const int BUFFER_SIZE = 1024;
        //socket
        public Socket socket;
        //是否使用 
        public bool isUse = false;
        //Buff
        public byte[] readBuff = new byte[BUFFER_SIZE];//读缓存区
        public int buffCount = 0;//当前读缓存区的长度
        //粘包分包
        public byte[] lenBytes = new byte[sizeof(UInt32)];
        public Int32 msglength = 0;
        //心跳时间 定时检测客户端和服务端是否连接
        public long lastTickTime = long.MinValue;
        //对应的player
        public Player player;

        //构造函数
        public Conn()
        { 
            //初始化缓存区
            readBuff = new byte[BUFFER_SIZE];
        }

        //初始化
        public void Init(Socket socket)
        {
            this.socket = socket;
            isUse = true;
            buffCount = 0;

            //心跳处理
            //lastTickTime = Sys.GetTimeStamp();
        }

        //剩余的buff
        public int BuffRemain()
        {
            return BUFFER_SIZE - buffCount;
        }

        //获取客户地址
        public string GetAdress()
        {
            if (!isUse) return "GetAdress fail";
            return socket.RemoteEndPoint.ToString();
        }

        //关闭
        public void Close()
        {
            if (!isUse) return;
            if (player != null)
            { 
                //玩家退出时操作
                //player.LoginOut();
                return;
            }
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
            isUse = false;
        }

        //发送协议
        //public void Send(ProtocolBase protocol)
        //{ 
            
        //}
    }
}
